//
//  SelectRoomViewController.m
//  QRMaster
//
//  Created by myApple on 15/6/16.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "SelectRoomViewController.h"
#import "DropDownMenuView.h"
#import "CommunityListModel.h"
#import "GuestCommunityChangeCell.h"
#import "RequestNetWork.h"
#import "OpertionPlist.h"
#import "QRSingleton.h"
#import "PromptInfoView.h"
#import "StartPageController.h"
#import "FloorsInfoLogic.h"
#import "BulidingInfoLogic.h"
#import "CardInfoModel.h"
#import "checkPower.h"
#import "RoomInfoLogic.h"
#import "CommunityListInfo.h"
#import "BackBtn.h"

@interface SelectRoomViewController ()<UITableViewDataSource,UITableViewDelegate,DropDownMenuViewDelegate>
{
    UITableView * leftTableView;
    UITableView * middleTableView;
    
    NSString * communityId;
    NSString * bulidingId;
    NSString * floorId;
    
    NSMutableArray * bulidingArray;
    NSMutableArray * floorArray;
    
    UIView * titleView;
    NSMutableArray * CommunityInfoArray;
    UIButton * communityNameBtn;
    
    UIButton * communityChangeBtn;
    UIImageView * ImgView;
    
    //下拉列表选择框
    DropDownMenuView * CommunityDDView;
    BOOL communityNameFlag;
    
    QRSingleton * singleton;
    
    UIControl * backViewControl;
}
@end

@implementation SelectRoomViewController

-(id)initWith:(NSString *)_communityId bulidingId:(NSString *)_bulidingId floorid:(NSString *)_floorId
{
    self = [super init];
    if (self) {
        communityId = _communityId;
        bulidingId = _bulidingId;
        floorId = _floorId;
        CommunityInfoArray = [[NSMutableArray alloc]init];
        bulidingArray = [[NSMutableArray alloc]init];
        floorArray = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    singleton = [QRSingleton sharedQRSingleton];
    self.navigationItem.title = NSLocalizedString(@"changefloor", nil);
    [self prepareTitleView];
    [self getInfo];
    [self getDataFromContentFile];
    [self prepareTabelView];
    [self prepareDropDownView];
    
    
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    titleView.hidden = NO;
//    communityChangeBtn.hidden = NO;
//    ImgView.hidden = NO;
//    communityNameBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    titleView.hidden = YES;
//    communityChangeBtn.hidden = YES;
//    ImgView.hidden = YES;
//    communityNameBtn.hidden = YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"moveWindown" object:nil];
}

-(void)getInfo
{
    
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase queryBulidingInfo:communityId block:^(NSMutableArray * bArray) {
        if (bArray.count > 0) {
            bulidingArray = bArray;
        }
    }];
    
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase queryFloorsInfo:bulidingId block:^(NSMutableArray *arr) {
        if (arr.count > 0) {
            floorArray = arr;
        }
    }];
    [leftTableView reloadData];
    [middleTableView reloadData];
    

}

-(void)checkCommunity
{
    [bulidingArray  removeAllObjects];
    [floorArray  removeAllObjects];
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase queryBulidingInfo:communityId block:^(NSMutableArray * bArray) {
        if (bArray.count > 0) {
            bulidingArray = bArray;
            BulidingModel * bModel = bArray[0];
            bulidingId = bModel.buildingId;
        }
    }];
    
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase queryFloorsInfo:bulidingId block:^(NSMutableArray *arr) {
        if (arr.count > 0) {
            floorArray = arr;
            FloorsModel * fModel = arr[0];
            floorId = fModel.floorId;
        }
    }];
    [leftTableView reloadData];
    [middleTableView reloadData];

}



#pragma mark -- 根据传过来的id号来请求房间数据
-(void)getHouseData
{
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    if([self getTimestamp:communityId timeKey:@"room_timestamp"] != nil)
    {
        [postDict setValue:[self getTimestamp:communityId timeKey:@"room_timestamp"] forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    [self startWaiting:nil color:nil addToView:self.view];
    [rnk initWithPath:POST(HOTELINFO) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        NSDictionary * cache = [downLoadData objectForKey:@"cache"];
        NSMutableArray * data = [downLoadData objectForKey:@"data"];
        if(cache != nil)
        {
            [self updateTimestamp:communityId timeKey:@"room_timestamp" timeKeyValue:[cache objectForKey:@"timestamp"]];
            
            if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[cache objectForKey:@"status"]]]==YES)
            {
                if (data != nil)
                {
                    [self deleteRooms];
                    bulidingArray = data;
                    [self insertDataIntoRooms:bulidingArray];
                }
            }
            [self checkCommunity];
            [leftTableView reloadData];
            [middleTableView reloadData];
        }
        else if (error != nil) {
            if ([[error objectForKey:@"status"]integerValue] == 301)
            {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
                [self failRequest];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }

    }];
    
}

-(void)prepareTitleView
{
    
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = 44;
    
//    titleView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    titleView.backgroundColor = [UIColor blackColor];
//    titleView.userInteractionEnabled = YES;
//    [self.navigationController.navigationBar addSubview:titleView];
    
    x = 10;
    y = 0;
    height = 40;
    width = 40;
    UIButton * backBtn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"navigationBack"];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
//    x = 50;
//    y = 5;
//    width = ScreenWidth - x - 70;
//    height = 34;
//    communityNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    communityNameBtn.frame = CGRectMake(x, y, width, height);
//    [communityNameBtn setTitleColor:[UIColor whiteColor] forState:0];
//    communityNameBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
//    [communityNameBtn addTarget:self action:@selector(ChangeCommunity) forControlEvents:UIControlEventTouchUpInside];
//    [titleView addSubview:communityNameBtn];
//    
//    x += width;
//    width = 15;
//    y = 14;
//    height = 15;
//    communityChangeBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    [communityChangeBtn setImage:[UIImage imageNamed:@"ic_triangle"] forState:0];
//    [communityChangeBtn addTarget:self action:@selector(ChangeCommunity) forControlEvents:UIControlEventTouchUpInside];
//    [titleView addSubview:communityChangeBtn];
//    
//    
//    x = ScreenWidth - 40;
//    width = 20;
//    y = 12;
//    height = 20;
//    ImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    ImgView.image = [UIImage imageNamed:@"ic_refresh"];
//    ImgView.userInteractionEnabled = YES;
//    [titleView addSubview:ImgView];
//    
//    UITapGestureRecognizer * refreshTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refreshClick)];
//    [ImgView addGestureRecognizer:refreshTap];
}

-(void)getDataFromContentFile
{
    [CommunityInfoArray removeAllObjects];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    NSArray * communityData = [data objectForKey:COMMUNITYINFOFORKEY];
     CommunityListInfo * listInfo = [[CommunityListInfo alloc]init];
    for (NSDictionary * dict in communityData) {
        CommunityListModel * model = [[CommunityListModel alloc]init];
        model.communityName = [dict objectForKey:@"communityname"];
        model.communityId = [dict objectForKey:@"communityid"];
        model.role = [dict objectForKey:@"role"];
        [CommunityInfoArray addObject:model];
        [listInfo deleteCommunityListInfo:[dict objectForKey:@"communityid"]];
        [listInfo insertCommunityListInfo:[dict objectForKey:@"communityid"] withCommunityName:[dict objectForKey:@"communityname"] withCommunityAreaCode:[dict objectForKey:@"communityid"]];
        if ([communityId isEqualToString:model.communityId]) {
            [communityNameBtn setTitle:model.communityName forState:0];
        }
    }
    
}

-(void)prepareDropDownView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 64;
    float width = ScreenWidth;
    float height = 0;
    
    //底部view让其下拉消失
    backViewControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, width, UI_SCREEN_HEIGHT)];
    backViewControl.alpha = 0.5;
    backViewControl.hidden = YES;
    [backViewControl addTarget:self action:@selector(removeDropDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backViewControl];
    
    CommunityDDView = [[DropDownMenuView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    CommunityDDView.delegate = self;
    CommunityDDView.hidden = YES;
    [backViewControl addSubview:CommunityDDView];
}

-(void)removeDropDown
{
    [CommunityDDView showOrNotList:YES];
    communityNameFlag = NO;
    backViewControl.hidden = YES;
}

-(void)ChangeCommunity
{
    if (communityNameFlag) {
        backViewControl.hidden = YES;
    }
    else
    {
        backViewControl.hidden = NO;
    }
    NSMutableArray * communityNameArray = [[NSMutableArray alloc]init];
    if (CommunityInfoArray.count) {
        for (CommunityListModel * model in CommunityInfoArray) {
            [communityNameArray addObject:model.communityName];
        }
        CommunityDDView.data = communityNameArray;
        [CommunityDDView showOrNotList:communityNameFlag];
        communityNameFlag =!communityNameFlag;
    }
    
    
}


#pragma mark === 刷新集群 如果有集群增加就要写文件更新
-(void)refreshClick
{
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak SelectRoomViewController * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        if ([data objectForKey:@"data"] != nil) {
            [weakSelf getDataFromContentFile];
        }
        else
        {
            if([[error objectForKey:@"status"]integerValue] == 210)
            {
                [PromptInfoView showMessage:NSLocalizedString(@"noAddCommunity", nil)];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }
        
    };
}


#pragma mark --- DropDownMenuViewDelegate
-(void)DropDownMenuView:(DropDownMenuView *)menuView showIndex:(int)index back:(BOOL)flag
{
    CommunityListModel * model = CommunityInfoArray[index];
    if (![model.communityId isEqualToString:communityId]) {
        communityId = model.communityId;
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"communityChangeByCardHouse" object:nil];
        [QRSingleton sharedQRSingleton].communityId = model.communityId;
        [QRSingleton sharedQRSingleton].currentAreaCodeString = model.areaCodeString;
        [[NSUserDefaults standardUserDefaults] setObject:model.communityId forKey:@"communityId"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        singleton.communityName = model.communityName;
        __weak SelectRoomViewController * weakSelf = self;
        
        bulidingId = @"";
        floorId = @"";
        [weakSelf getHouseData];
    }
    [communityNameBtn setTitle:model.communityName forState:0];
    communityNameFlag = flag;
    backViewControl.hidden = YES;
}

//网络请求失败
-(void)failRequest
{
    [self deleteRooms];
    bulidingArray = nil;
    floorArray = nil;
    [leftTableView reloadData];
    [middleTableView reloadData];
    if (_houseInfo) {
        singleton.communityName = communityNameBtn.titleLabel.text;
        self.houseInfo(communityId,bulidingId,floorId);
    }
}

-(void)prepareTabelView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth / 2.0;
    float height = ScreenHeight - y;
    
    leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    leftTableView.delegate = self;
    leftTableView.dataSource = self;
    leftTableView.backgroundColor = RGBA(237, 238, 241, 1);
    leftTableView.separatorStyle = NO;
    [self.view addSubview:leftTableView];
    
    
    x += width;
    width = ScreenWidth / 2.0;
    middleTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    middleTableView.delegate = self;
    middleTableView.dataSource = self;
    middleTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:middleTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == leftTableView) {
        return bulidingArray.count;
    }
    else
    {
        return floorArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    GuestCommunityChangeCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[GuestCommunityChangeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    if (tableView == leftTableView) {
        if (bulidingArray.count > indexPath.row) {
            BulidingModel * bModel = bulidingArray[indexPath.row];
            if (bModel.buildingName==nil || [bModel.buildingId isEqualToString:@""]) {
                cell.cellName=@"";
            }
            else
            {
            cell.cellName = bModel.buildingName;
            }
            cell.backgroundColor = RGBA(237, 238, 241, 1);
            if ([bulidingId isEqualToString:bModel.buildingId]) {
                cell.backgroundColor = [UIColor whiteColor];
            }
        }
    }
    else
    {
        if (floorArray.count > indexPath.row) {
            FloorsModel * fModel = floorArray[indexPath.row];
            cell.cellName = fModel.floorName;
            if ([floorId isEqualToString:fModel.floorId]){
                cell.selectOrNot = YES;
            }
            else
            {
                cell.selectOrNot = NO;
            }
        }
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == leftTableView) {
        BulidingModel * bModel = bulidingArray[indexPath.row];
        bulidingId = bModel.buildingId;
        [self RefreshHouseData:(int)indexPath.row];
    }
    else if(tableView == middleTableView)
    {
        if ([self IsHaveNetwork] == NO ) {
            FloorsModel * fModel = floorArray[indexPath.row];
            floorId = fModel.floorId;
        if (_houseInfo) {
//            singleton.communityName = communityNameBtn.titleLabel.text;
            self.houseInfo(communityId,bulidingId,floorId);
        }
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(void)clickBack
{
    if (_houseInfo) {
        self.houseInfo(communityId,bulidingId,floorId);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark  根据传进来的下标来更新楼栋，楼层，房间
/*
 index 下标
 flag 0表示楼栋改变了，1表示楼层改变了
 */
-(void)RefreshHouseData:(int )index
{
    [leftTableView reloadData];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase queryFloorsInfo:bulidingId block:^(NSMutableArray *arr) {
        floorArray = arr;
    }];
    [middleTableView reloadData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)deleteRooms
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase deleteBulidingWithCommunityId:communityId];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase deleteFloorsInfoWithCommunityId:communityId];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    [roomDataBase deleteRoomWithCommunityId:communityId];
    bulidingId = @"";
    floorId = @"";
}

-(void)insertDataIntoRooms:(NSArray *)allBuildingInfo
{
    if (allBuildingInfo.count == 0) {
        return;
    }
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    for (NSDictionary * bDict in allBuildingInfo)
    {
        BulidingModel * bModel = [[BulidingModel alloc]init];
        bModel.buildingName = [bDict objectForKey:@"buildingname"];
        bModel.buildingId = [bDict objectForKey:@"buildingid"];
        bModel.buildingNo = [bDict objectForKey:@"buildingno"];
        [bulidingDataBase insertBulidingInfo:bModel withCommunityId:communityId];
        bModel.floors = [bDict objectForKey:@"floors"];
        for (NSDictionary * fDict in bModel.floors) {
            FloorsModel * fModel = [[FloorsModel alloc]init];
            fModel.floorId = [fDict objectForKey:@"floorid"];
            fModel.floorName = [fDict objectForKey:@"floorname"];
            fModel.floorNo  = [fDict objectForKey:@"floorno"];
            [floorDataBase insertFloorInfo:fModel withCommunityId:communityId buildingId:bModel.buildingId];
            fModel.rooms = [fDict objectForKey:@"rooms"];
            for (NSDictionary * rDict in fModel.rooms) {
                RoomsModel * rModel = [[RoomsModel alloc]init];
                rModel.roomId = [rDict objectForKey:@"roomid"];
                rModel.roomName = [rDict objectForKey:@"roomname"];
                rModel.roomNo = [rDict objectForKey:@"roomno"];
                rModel.isSelect = [rDict objectForKey:@"isSelected"];
                rModel.lockNo = [rDict objectForKey:@"lockno"];
                rModel.occupation = [rDict objectForKey:@"occupation"];
                [roomDataBase insertRoomInfo:rModel withFloorId:fModel.floorId withCommunityId:communityId];
            }
        }
    }
}



@end
